package apigateway.project.configcenter.Impl;

import apigateway.project.commen.config.Rule;
import apigateway.project.configcenter.NacosConfigCenter;
import apigateway.project.configcenter.RulesChangeListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Executor;

@Slf4j
public class NacosConfigCenterImpl implements NacosConfigCenter {

    private String serverAddress;

    private String dataId;

    private String groupId;

    private ConfigService configService;

    @Override
    public void init(String serverAddress,String dataId,String groupId) {
        this.serverAddress = serverAddress;
        this.dataId = dataId;
        this.groupId = groupId;
        try {
            this.configService = NacosFactory.createConfigService(serverAddress);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void pullConfigAndListener(RulesChangeListener rulesChangeListener) {
        try {
            String config = configService.getConfig(dataId, groupId, 5000);
            log.info("初始的config为:{}",config);
            List<Rule> rules = JSON.parseObject(config).getJSONArray("rules").toJavaList(Rule.class);
//            for (Rule rule : rules) {
//                log.info("rule:{}",rule);
//            }
            rulesChangeListener.rulesChanged(rules);
            configService.addListener(dataId, groupId, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String s) {
                    log.info("config更新为：{}",s);
                    List<Rule> rules = JSON.parseObject(s).getJSONArray("rules").toJavaList(Rule.class);
                    rulesChangeListener.rulesChanged(rules);
                }
            });
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }
}
